<template>
  <el-dialog destroy-on-close draggable title="Merge" width="400" v-model="visible">
    <el-form :model="formParam" ref="custForm" :rules="rules">
      <el-form-item label="B/L No" label-width="120px" prop="id" required>
        <el-select v-model="formParam.id" filterable clearable>
          <el-option :key="item.value" :label="item.label" :value="item.value" v-for="item in idOptions"></el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <div class="footer-add" v-if="formParam.id">
      <div style="display: flex;">
        <PreViewImageUpload :url="uploadUrl" :id="formParam.id" type="1" :isTable="false" :accept="accept"
          :dataName="'id,type'" @onSuccess="uploadSuccess" />
        <span v-show="!formParam.combineFileUrl">Upload LOI</span>
      </div>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="visible = false">{{ $t("ship.button.cancel") }}</el-button>
        <el-button type="primary" :loading="isLoading" @click="onSubmit">{{ $t("ship.button.submit") }}</el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script setup lang="ts" name="MergeModal">
  import { ElMessageBox } from "element-plus";
  import { ref, reactive, defineExpose, getCurrentInstance } from 'vue';
  import service from "@/utils/request";
  import PreViewImageUpload from '@/components/ImageUpload/PreViewImageUpload.vue'

  const proxy = getCurrentInstance()?.proxy
  const visible = ref(false);
  const isLoading = ref(false)

  const rules = ref({
    id: [{ required: true, message: "B/L NO. can't be blank" }]
  });

  const formParam = reactive({
    id: null,
    details: []
  })

  const onInit = ({ details }) => {
    visible.value = true;
    formParam.id = null;
    formParam.details = details;
  }

  const idOptions = computed(() => {
    return formParam.details.map(item => {
      return {
        label: item.blNo,
        value: item.id
      }
    })
  })

  const onSubmit = () => {
    proxy.$refs["custForm"].validate(valid => {
      if (valid) {
        ElMessageBox.confirm("Confirm to combine the data？", "Confirmation Information", {
          type: "warning",
          confirmButtonText: "Confirm",
          cancelButtonText: "Cancel"
        }).then(async () => {
          isLoading.value = true;
          service.post("/shipping/cargoManifest/combine", formParam).then(() => {
            proxy.$emit("success");
            visible.value = false;
          }).finally(() => {
            isLoading.value = false;
          })
        })
      }
    })
  }
  // 上传凭证
  const accept = ref('.pdf');
  const uploadUrl = ref("/shipping/cargoManifest/uploadVoucher");
  const uploadSuccess = (data) => {
    formParam.combineFileUrl = data.photos[0]
  }
  defineExpose({ onInit });
</script>
<style scoped lang="scss">
  .footer-add {
    display: flex;
    line-height: 32px;
    justify-content: space-between;
    margin-top: 10px;
  }
</style>